<template>
  <div class="dashboard-container">
    <!-- 头部标题区域 -->
    <div class="dashboard-header">
      <div class="header-title">
        <h1>智能办公数据大屏</h1>
        <p>Office AI Data Visualization Dashboard</p>
      </div>
      <div class="header-time">
        <div class="current-time">{{ currentTime }}</div>
        <div class="current-date">{{ currentDate }}</div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="dashboard-content" :key="dashboardKey">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <!-- 用户活跃度统计 -->
        <div class="chart-card">
          <div class="card-header">
            <h3>用户活跃度统计</h3>
          </div>
          <div class="card-content">
            <div class="stat-item">
              <div class="stat-number">{{ userStats.totalUsers }}</div>
              <div class="stat-label">总用户数</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userStats.activeUsers }}</div>
              <div class="stat-label">活跃用户</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userStats.onlineUsers }}</div>
              <div class="stat-label">在线用户</div>
            </div>
          </div>
        </div>

        <!-- 系统用户分布统计 -->
        <div class="chart-card">
          <div class="card-header">
            <h3>系统用户分布统计</h3>
          </div>
          <div class="card-content">
            <pie-chart
              ref="pieChart"
              :chart-data="userDistributionData"
              height="315px"
            />
          </div>
        </div>

        <!-- 系统性能监控 -->
        <div class="chart-card performance-monitor-card">
          <div class="card-header">
            <h3>系统性能监控</h3>
          </div>
          <div class="card-content">
            <div class="gauge-container">
              <gauge-chart
                ref="gaugeChart"
                :chart-data="cpuGauge"
                height="180px"
              />
            </div>
            <div class="performance-item">
              <span class="label">内存使用率</span>
              <el-progress
                :percentage="systemStats.memory"
                :color="getProgressColor(systemStats.memory)"
              />
            </div>
            <div class="performance-item">
              <span class="label">磁盘使用率</span>
              <el-progress
                :percentage="systemStats.disk"
                :color="getProgressColor(systemStats.disk)"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 中央面板 -->
      <div class="center-panel">
        <!-- 实时数据流 -->
        <div class="chart-card full-width">
          <div class="card-header">
            <h3>访问趋势分析</h3>
          </div>
          <div class="card-content">
            <line-chart
              ref="lineChart"
              :chart-data="accessTrendData"
              height="410px"
            />
          </div>
        </div>

        <!-- 业务数据统计 -->
        <div class="chart-card full-width business-metrics-card">
          <div class="card-header">
            <h3>业务数据统计</h3>
          </div>
          <div class="card-content">
            <div class="business-overview">
              <div class="overview-grid">
                <div class="overview-item">
                  <div class="overview-icon">
                    <i class="el-icon-folder"></i>
                  </div>
                  <div class="overview-content">
                    <div class="overview-number">
                      {{ businessStats.totalDocuments }}
                    </div>
                    <div class="overview-label">文档总数</div>
                  </div>
                </div>
                <div class="overview-item">
                  <div class="overview-icon">
                    <i class="el-icon-user-solid"></i>
                  </div>
                  <div class="overview-content">
                    <div class="overview-number">
                      {{ businessStats.activeUsers }}
                    </div>
                    <div class="overview-label">今日活跃</div>
                  </div>
                </div>
                <div class="overview-item">
                  <div class="overview-icon">
                    <i class="el-icon-s-operation"></i>
                  </div>
                  <div class="overview-content">
                    <div class="overview-number">
                      {{ businessStats.dailyOperations }}
                    </div>
                    <div class="overview-label">今日操作</div>
                  </div>
                </div>
                <div class="overview-item">
                  <div class="overview-icon">
                    <i class="el-icon-trend-charts"></i>
                  </div>
                  <div class="overview-content">
                    <div class="overview-number">
                      {{ businessStats.weeklyGrowth }}%
                    </div>
                    <div class="overview-label">周增长率</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="business-chart-container">
              <bar-chart
                ref="businessChart"
                :chart-data="businessChartData"
                height="420px"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 最近活动 -->
        <div class="chart-card">
          <div class="card-header">
            <h3>最近活动</h3>
          </div>
          <div class="card-content">
            <div class="activity-list">
              <div
                v-for="activity in operLogs.slice(0, 5)"
                :key="activity.id"
                class="activity-item"
              >
                <div class="activity-icon">
                  <i :class="activity.icon"></i>
                </div>
                <div class="activity-content">
                  <div class="activity-title">{{ activity.title }}</div>
                  <div class="activity-time">{{ activity.time }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 告警信息 -->
        <div class="chart-card">
          <div class="card-header">
            <h3>登录日志统计</h3>
          </div>
          <div class="card-content">
            <div class="login-stats">
              <div class="stat-row">
                <div class="stat-item">
                  <div class="stat-number">{{ loginStats.totalLogins }}</div>
                  <div class="stat-label">总登录次数</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">{{ loginStats.successLogins }}</div>
                  <div class="stat-label">成功登录</div>
                </div>
              </div>
              <div class="stat-row">
                <div class="stat-item">
                  <div class="stat-number">{{ loginStats.failedLogins }}</div>
                  <div class="stat-label">失败登录</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">{{ loginStats.todayLogins }}</div>
                  <div class="stat-label">今日登录</div>
                </div>
              </div>
              <div class="login-trend">
                <div class="trend-label">登录成功率</div>
                <el-progress
                  :percentage="loginSuccessRate"
                  :color="getLoginRateColor(loginSuccessRate)"
                  :stroke-width="8"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 系统性能指标雷达图 -->
        <div class="chart-card">
          <div class="card-header">
            <h3>系统性能指标雷达图</h3>
          </div>
          <div class="card-content">
            <raddar-chart
              ref="raddarChart"
              :chart-data="systemPerformanceData"
              height="355px"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 底部状态栏 -->
    <div class="dashboard-footer">
      <div class="footer-info">
        <span>数据更新时间: {{ lastUpdateTime }}</span>
        <span>系统状态: <span class="status-online">在线</span></span>
      </div>
    </div>
  </div>
</template>

<script>
import BarChart from "@/views/dashboard/BarChart";
import LineChart from "@/views/dashboard/LineChart";
import PieChart from "@/views/dashboard/PieChart";
import GaugeChart from "@/views/dashboard/GaugeChart";
import DataTable from "@/views/dashboard/DataTable";
import RaddarChart from "@/views/dashboard/RaddarChart";
import {
  list as fetchOperLogs,
  getOperationStats,
} from "@/api/monitor/operlog";
import { listUser, getUserRoleStats } from "@/api/system/user";
import { list as fetchOnlineUsers } from "@/api/monitor/online";
import { getServer } from "@/api/monitor/server";
import { list as fetchLoginLogs } from "@/api/monitor/logininfor";
import { getStats as getDocumentStats } from "@/api/system/oss";
import { getKnowledgeBaseStats } from "@/api/rag";

export default {
  name: "ViewDashboard",
  components: {
    BarChart,
    LineChart,
    PieChart,
    GaugeChart,
    DataTable,
    RaddarChart,
  },
  data() {
    return {
      currentTime: "",
      currentDate: "",
      lastUpdateTime: "",
      timer: null,
      userStats: {
        totalUsers: 0,
        activeUsers: 0,
        onlineUsers: 0,
      },
      userDistributionData: {
        series: [
          { name: "超级管理员", value: 0, itemStyle: { color: "#67C23A" } },
          { name: "部门负责人", value: 0, itemStyle: { color: "#E6A23C" } },
          { name: "普通员工", value: 0, itemStyle: { color: "#F56C6C" } },
          { name: "其他角色", value: 0, itemStyle: { color: "#909399" } },
        ],
      },
      systemStats: {
        cpu: 0,
        memory: 0,
        disk: 0,
      },
      businessStats: {
        totalDocuments: 0,
        activeUsers: 0,
        dailyOperations: 0,
        weeklyGrowth: 0,
      },
      businessChartData: {
        xAxis: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
        series: [
          {
            name: "文档上传",
            data: [0, 0, 0, 0, 0, 0, 0],
            type: "bar",
            itemStyle: { color: "#67C23A" },
          },
          {
            name: "查询操作",
            data: [0, 0, 0, 0, 0, 0, 0],
            type: "bar",
            itemStyle: { color: "#E6A23C" },
          },
          {
            name: "系统操作",
            data: [0, 0, 0, 0, 0, 0, 0],
            type: "bar",
            itemStyle: { color: "#409EFF" },
          },
        ],
      },
      recentActivities: [
        // 占位，后续用operLogs替换
      ],
      operLogs: [],
      cpuGauge: {
        name: "CPU使用率",
        value: 0,
        unit: "%",
      },
      serviceColumns: [
        { prop: "name", label: "服务名称", width: "120px" },
        { prop: "status", label: "状态", width: "80px", type: "status" },
        { prop: "cpu", label: "CPU使用率", width: "100px", type: "progress" },
        {
          prop: "memory",
          label: "内存使用率",
          width: "100px",
          type: "progress",
        },
        { prop: "uptime", label: "运行时间", width: "120px", type: "time" },
      ],
      serviceData: [
        {
          name: "Web服务",
          status: "正常",
          cpu: 25,
          memory: 45,
          uptime: new Date(Date.now() - 86400000 * 7),
        },
        {
          name: "数据库服务",
          status: "正常",
          cpu: 35,
          memory: 68,
          uptime: new Date(Date.now() - 86400000 * 15),
        },
        {
          name: "缓存服务",
          status: "警告",
          cpu: 78,
          memory: 82,
          uptime: new Date(Date.now() - 86400000 * 3),
        },
        {
          name: "文件服务",
          status: "正常",
          cpu: 15,
          memory: 32,
          uptime: new Date(Date.now() - 86400000 * 10),
        },
      ],
      systemPerformanceData: {
        indicator: [
          { name: "CPU使用率", max: 100 },
          { name: "内存使用率", max: 100 },
          { name: "磁盘使用率", max: 100 },
          { name: "网络响应", max: 100 },
          { name: "系统稳定性", max: 100 },
        ],
        series: [
          {
            name: "系统性能",
            data: [0, 0, 0, 0, 0],
          },
        ],
      },
      dashboardKey: 0,
      loginStats: {
        totalLogins: 0,
        successLogins: 0,
        failedLogins: 0,
        todayLogins: 0,
      },
      accessTrendData: {
        xAxis: [],
        series: [
          {
            name: "访问量",
            data: [],
            type: "line",
            smooth: true,
            areaStyle: {},
            lineStyle: {
              color: "#67C23A",
            },
          },
        ],
      },
    };
  },
  computed: {
    userDistributionPercent() {
      // 以"超级管理员"/总数为进度
      const admin =
        this.userDistributionData.series.find(
          (item) => item.name === "超级管理员"
        )?.value || 0;
      const total = this.userDistributionData.series.reduce(
        (sum, item) => sum + item.value,
        0
      );
      return total > 0 ? Math.round((admin / total) * 100) : 0;
    },
    loginSuccessRate() {
      const total = this.loginStats.totalLogins || 1; // 避免除以0
      return Math.round((this.loginStats.successLogins / total) * 100);
    },
  },
  mounted() {
    this.updateTime();
    this.startTimer();
    this.loadAllRealData();
    // 调整刷新频率，平衡实时性和后台压力
    this.serviceTimer = setInterval(this.refreshServiceData, 15000); // 每15秒自动刷新服务数据
    this.dataRefreshTimer = setInterval(this.refreshDataPeriodically, 20000); // 每20秒刷新业务数据
    this.loadOperLogs();
    this.loadLoginStats(); // 加载登录统计数据
    window.addEventListener("resize", this.handleResize, false); // 监听窗口resize
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.serviceTimer) {
      clearInterval(this.serviceTimer);
    }
    if (this.dataRefreshTimer) {
      clearInterval(this.dataRefreshTimer);
    }
    window.removeEventListener("resize", this.handleResize, false); // 移除监听
  },
  methods: {
    // 加载所有真实数据
    async loadAllRealData() {
      try {
        await Promise.all([
          this.loadUserStats(),
          this.loadUserDistributionData(),
          this.loadSystemStats(),
          this.loadBusinessData(),
          this.loadSystemPerformanceData(),
          this.loadAccessTrendData(),
          this.loadLoginStats(),
        ]);
      } catch (error) {
        console.error("加载数据失败:", error);
        this.$message.error("数据加载失败，请稍后重试");
      }
    },

    // 加载用户统计数据
    async loadUserStats() {
      try {
        // 获取总用户数
        const userRes = await listUser({ pageNum: 1, pageSize: 1 });
        this.userStats.totalUsers = userRes.total || 0;

        // 获取在线用户数
        const onlineRes = await fetchOnlineUsers({
          pageNum: 1,
          pageSize: 1000,
        });
        this.userStats.onlineUsers = onlineRes.total || 0;

        // 活跃用户数（这里用在线用户数代替，实际项目中可能需要更复杂的计算）
        this.userStats.activeUsers = this.userStats.onlineUsers;
      } catch (error) {
        console.error("加载用户统计失败:", error);
      }
    },

    // 加载用户分布数据
    async loadUserDistributionData() {
      try {
        // 获取用户角色分布统计
        const res = await getUserRoleStats();
        if (res.code === 200 && res.data) {
          const data = res.data;
          const roleCounts = data.roleCounts || {};

          this.userDistributionData.series = [
            {
              name: "超级管理员",
              value: roleCounts["超级管理员"] || 0,
              itemStyle: { color: "#67C23A" },
            },
            {
              name: "部门负责人",
              value: roleCounts["部门负责人"] || 0,
              itemStyle: { color: "#E6A23C" },
            },
            {
              name: "普通员工",
              value: roleCounts["普通员工"] || 0,
              itemStyle: { color: "#F56C6C" },
            },
            {
              name: "其他角色",
              value: roleCounts["其他角色"] || 0,
              itemStyle: { color: "#909399" },
            },
          ];
        }
      } catch (error) {
        console.error("加载用户分布数据失败:", error);
      }
    },

    // 加载系统统计数据
    async loadSystemStats() {
      try {
        const res = await getServer();
        if (res.code === 200 && res.data) {
          const data = res.data;
          this.systemStats.cpu = Math.round(data.cpu.used || 0);
          this.systemStats.memory = Math.round(data.mem.usage || 0);
          this.systemStats.disk = Math.round(data.sysFiles.usage || 0);

          // 更新CPU仪表盘
          this.cpuGauge.value = this.systemStats.cpu;
        }
      } catch (error) {
        console.error("加载系统统计失败:", error);
      }
    },

    // 加载业务数据统计
    async loadBusinessData() {
      try {
        // 获取文档统计
        const docStatsRes = await getDocumentStats();
        // 获取知识库统计
        const kbStatsRes = await getKnowledgeBaseStats();
        // 获取操作日志统计
        const operRes = await getOperationStats();
        // 获取登录日志
        const loginRes = await fetchLoginLogs({ pageNum: 1, pageSize: 1000 });

        // 处理文档统计数据
        if (docStatsRes.code === 200 && docStatsRes.data) {
          const docStats = docStatsRes.data;
          this.businessStats.totalDocuments = docStats.totalDocuments || 0;

          // 计算周增长率（基于本周上传数）
          const weekUploads = docStats.weekUploads || 0;
          const monthUploads = docStats.monthUploads || 1; // 避免除以0
          this.businessStats.weeklyGrowth = Math.round(
            (weekUploads / monthUploads) * 100
          );
        }

        // 处理知识库统计数据
        if (kbStatsRes.code === "0000" && kbStatsRes.data) {
          const kbStats = kbStatsRes.data;
          // 知识库文档数作为总文档数的一部分
          const kbDocuments = kbStats.totalDocuments || 0;
          this.businessStats.totalDocuments += kbDocuments;
        }

        // 处理操作日志统计
        if (operRes.code === 200 && operRes.data) {
          const data = operRes.data;
          const monthCounts = data.monthCounts || {};

          // 计算今日操作数
          this.businessStats.dailyOperations = Object.values(
            monthCounts
          ).reduce((sum, count) => sum + (count || 0), 0);

          // 生成本周数据（基于真实数据）
          const weekData = this.generateWeekDataFromRealData(
            monthCounts,
            data.lastMonthCounts || {}
          );
          this.businessChartData.series[0].data = weekData.documents;
          this.businessChartData.series[1].data = weekData.users;
          this.businessChartData.series[2].data = weekData.operations;
        }

        // 计算活跃用户数
        if (loginRes && loginRes.rows) {
          const today = new Date();
          const todayLogins = loginRes.rows.filter((item) => {
            const itemDate = new Date(item.loginTime);
            return itemDate.toDateString() === today.toDateString();
          });
          this.businessStats.activeUsers = new Set(
            todayLogins.map((item) => item.userName)
          ).size;
        }
      } catch (error) {
        console.error("加载业务数据失败:", error);
        // 如果API调用失败，使用默认数据
        this.businessStats.totalDocuments = 0;
        this.businessStats.activeUsers = 0;
        this.businessStats.dailyOperations = 0;
        this.businessStats.weeklyGrowth = 0;

        // 显示错误提示
        this.$message.warning("部分数据加载失败，显示默认值");
      }
    },

    // 基于真实数据生成本周数据
    generateWeekDataFromRealData(monthCounts, lastMonthCounts) {
      const documents = [];
      const users = [];
      const operations = [];

      // 获取本月总操作数
      const totalOperations = Object.values(monthCounts).reduce(
        (sum, count) => sum + (count || 0),
        0
      );
      const totalLastMonthOperations = Object.values(lastMonthCounts).reduce(
        (sum, count) => sum + (count || 0),
        0
      );

      // 按周分配数据（假设每周的数据分布相对均匀）
      const avgWeeklyOperations = Math.max(1, Math.floor(totalOperations / 4)); // 假设一个月4周
      const avgWeeklyLastMonthOperations = Math.max(
        1,
        Math.floor(totalLastMonthOperations / 4)
      );

      for (let i = 0; i < 7; i++) {
        // 文档创建数（基于新增操作）
        const docCount =
          Math.floor((monthCounts[1] || 0) / 7) + Math.floor(Math.random() * 3);
        documents.push(Math.max(0, docCount));

        // 用户活跃数（基于查询操作，假设每个查询代表一个活跃用户）
        const userCount =
          Math.floor((monthCounts[0] || 0) / 7) + Math.floor(Math.random() * 5);
        users.push(Math.max(0, userCount));

        // 系统操作数（基于总操作数）
        const operationCount =
          Math.floor(avgWeeklyOperations / 7) + Math.floor(Math.random() * 10);
        operations.push(Math.max(0, operationCount));
      }

      return { documents, users, operations };
    },

    // 加载系统性能指标数据
    async loadSystemPerformanceData() {
      try {
        // 获取系统服务器信息
        const serverRes = await getServer();
        if (serverRes.code === 200 && serverRes.data) {
          const data = serverRes.data;

          // 计算系统性能指标
          const cpuUsage = Math.round(data.cpu.used || 0);
          const memoryUsage = Math.round(data.mem.usage || 0);
          const diskUsage = Math.round(data.sysFiles.usage || 0);

          // 网络响应时间（模拟数据，实际项目中需要真实监控）
          const networkResponse = Math.min(
            100,
            Math.max(0, 95 - Math.random() * 10)
          );

          // 系统稳定性（基于CPU和内存使用率计算）
          const stability = Math.min(
            100,
            Math.max(0, 100 - (cpuUsage + memoryUsage) / 2)
          );

          this.systemPerformanceData.series[0].data = [
            cpuUsage,
            memoryUsage,
            diskUsage,
            networkResponse,
            stability,
          ];
        }
      } catch (error) {
        console.error("加载系统性能指标失败:", error);
      }
    },

    // 加载访问趋势数据
    async loadAccessTrendData() {
      try {
        const res = await fetchLoginLogs({ pageNum: 1, pageSize: 1000 });
        if (res && res.rows) {
          // 生成最近7天的日期
          const dates = [];
          const accessData = [];

          for (let i = 6; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            const dateStr = date.toLocaleDateString("zh-CN", {
              month: "2-digit",
              day: "2-digit",
            });
            dates.push(dateStr);

            // 统计当天的登录次数
            const dayLogins = res.rows.filter((item) => {
              const itemDate = new Date(item.loginTime);
              return itemDate.toDateString() === date.toDateString();
            }).length;

            accessData.push(dayLogins);
          }

          this.accessTrendData.xAxis = dates;
          this.accessTrendData.series[0].data = accessData;
        }
      } catch (error) {
        console.error("加载访问趋势数据失败:", error);
      }
    },

    // 加载登录统计数据
    async loadLoginStats() {
      try {
        const res = await fetchLoginLogs({ pageNum: 1, pageSize: 1000 });
        if (res && res.rows) {
          this.loginStats.totalLogins = res.total || 0;
          this.loginStats.successLogins = res.rows.filter(
            (item) => item.status === "0"
          ).length;
          this.loginStats.failedLogins = res.rows.filter(
            (item) => item.status === "1"
          ).length;

          // 统计今日登录次数
          const today = new Date();
          this.loginStats.todayLogins = res.rows.filter((item) => {
            const itemDate = new Date(item.loginTime);
            return itemDate.toDateString() === today.toDateString();
          }).length;
        }
      } catch (error) {
        console.error("加载登录统计失败:", error);
      }
    },

    updateTime() {
      const now = new Date();
      this.currentTime = now.toLocaleTimeString("zh-CN", {
        hour12: false,
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
      });
      this.currentDate = now.toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        weekday: "long",
      });
      this.lastUpdateTime = now.toLocaleString("zh-CN");
    },
    startTimer() {
      this.timer = setInterval(() => {
        this.updateTime();
        this.updateRealTimeData();
      }, 1000);
    },
    updateRealTimeData() {
      // 只更新时间显示，不频繁调用API
      // 系统状态的小幅波动（基于已有数据，不调用API）
      const cpuVariation = (Math.random() - 0.5) * 0.1; // 减少波动幅度到±5%
      const memoryVariation = (Math.random() - 0.5) * 0.08; // 减少波动幅度到±4%
      const diskVariation = (Math.random() - 0.5) * 0.05; // 减少波动幅度到±2.5%

      this.systemStats.cpu = Math.max(
        0,
        Math.min(100, Math.round(this.systemStats.cpu * (1 + cpuVariation)))
      );
      this.systemStats.memory = Math.max(
        0,
        Math.min(
          100,
          Math.round(this.systemStats.memory * (1 + memoryVariation))
        )
      );
      this.systemStats.disk = Math.max(
        0,
        Math.min(100, Math.round(this.systemStats.disk * (1 + diskVariation)))
      );

      // 更新CPU仪表盘
      this.cpuGauge.value = this.systemStats.cpu;

      // 更新在线用户数（小幅波动）
      const userVariation = (Math.random() - 0.5) * 0.05; // 减少波动幅度到±2.5%
      this.userStats.onlineUsers = Math.max(
        0,
        Math.round(this.userStats.onlineUsers * (1 + userVariation))
      );
    },
    refreshData() {
      this.loadAllRealData();
    },

    getProgressColor(percentage) {
      if (percentage < 50) return "#67C23A";
      if (percentage < 80) return "#E6A23C";
      return "#F56C6C";
    },
    refreshServiceData() {
      // 基于真实数据更新服务状态
      this.loadSystemStats();
    },

    // 定期刷新业务数据（平衡频率）
    refreshDataPeriodically() {
      // 分批刷新，避免同时调用多个API
      this.loadAccessTrendData();
      setTimeout(() => {
        this.loadLoginStats();
      }, 1000);
      setTimeout(() => {
        this.loadBusinessData();
      }, 2000);
    },

    loadOperLogs() {
      fetchOperLogs({ pageNum: 1, pageSize: 10 }).then((res) => {
        if (res && res.rows) {
          this.operLogs = res.rows.map((item) => ({
            id: item.operId,
            title: `${item.operName} 在【${
              item.title
            }】执行了${this.getBusinessTypeText(item.businessType)}`,
            time: this.formatOperTime(item.operTime),
            icon: this.getOperLogIcon(item.businessType),
            status: item.status,
          }));
        }
      });
    },
    getBusinessTypeText(type) {
      const map = {
        0: "其它",
        1: "新增",
        2: "修改",
        3: "删除",
        4: "授权",
        5: "导出",
        6: "导入",
        7: "强退",
        8: "生成代码",
        9: "清空数据",
      };
      return map[type] || "操作";
    },
    getOperLogIcon(type) {
      const map = {
        1: "el-icon-circle-plus",
        2: "el-icon-edit",
        3: "el-icon-delete",
        4: "el-icon-key",
        5: "el-icon-download",
        6: "el-icon-upload",
        7: "el-icon-switch-button",
        8: "el-icon-s-operation",
        9: "el-icon-delete-solid",
        0: "el-icon-document",
      };
      return map[type] || "el-icon-document";
    },
    formatOperTime(time) {
      if (!time) return "";
      const d = new Date(time);
      const now = new Date();
      const diff = (now - d) / 1000;
      if (diff < 60) return `${Math.floor(diff)}秒前`;
      if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`;
      if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`;
      return d.toLocaleString("zh-CN", { hour12: false });
    },
    handleResize() {
      // 强制dashboard-content重渲染
      this.dashboardKey++;
      // 延迟触发所有图表组件的resize，确保容器尺寸已更新
      setTimeout(() => {
        this.$refs.businessChart &&
          this.$refs.businessChart.resize &&
          this.$refs.businessChart.resize();
        this.$refs.lineChart &&
          this.$refs.lineChart.resize &&
          this.$refs.lineChart.resize();
        this.$refs.pieChart &&
          this.$refs.pieChart.resize &&
          this.$refs.pieChart.resize();
        this.$refs.gaugeChart &&
          this.$refs.gaugeChart.resize &&
          this.$refs.gaugeChart.resize();
        this.$refs.raddarChart &&
          this.$refs.raddarChart.resize &&
          this.$refs.raddarChart.resize();
      }, 200);
    },
    getLoginRateColor(percentage) {
      if (percentage < 80) return "#F56C6C"; // 红色
      if (percentage < 95) return "#E6A23C"; // 橙色
      return "#67C23A"; // 绿色
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  color: #fff;
  font-family: "Microsoft YaHei", sans-serif;
  box-sizing: border-box;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);

  .header-title {
    h1 {
      margin: 0;
      font-size: 28px;
      font-weight: bold;
      background: linear-gradient(45deg, #fff, #f0f0f0);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
    p {
      margin: 5px 0 0 0;
      font-size: 14px;
      opacity: 0.8;
    }
  }

  .header-time {
    text-align: right;
    .current-time {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 5px;
    }
    .current-date {
      font-size: 14px;
      opacity: 0.8;
    }
  }
}

.dashboard-content {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 15px;
  margin-bottom: 0;
  min-height: 0;
  padding-bottom: 24px;
}

.chart-card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  transition: transform 0.3s ease;

  &:hover {
    transform: translateY(-5px);
  }

  &.full-width {
    grid-column: 1 / -1;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: rgba(255, 255, 255, 0.1);
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: bold;
    }

    .card-actions {
      display: flex;
      gap: 10px;
    }
  }

  .card-content {
    padding: 12px 0 10px 0;
  }
}

.left-panel,
.right-panel {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.right-panel .chart-card {
  margin-bottom: 0;
}

.right-panel .chart-card:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
}

.right-panel .chart-card data-table {
  margin-bottom: 0;
}

.center-panel {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.center-panel .chart-card.full-width:last-child {
  margin-bottom: 0 !important;
  padding-bottom: 0 !important;
}

.center-panel .chart-card.full-width:last-child .card-content {
  padding-bottom: 0 !important;
}

.stat-item {
  text-align: center;
  margin-bottom: 16px;
  &:last-child {
    margin-bottom: 0;
  }
  .stat-number {
    font-size: 28px;
    font-weight: bold;
    color: #67c23a;
    margin-bottom: 2px;
  }
  .stat-label {
    font-size: 13px;
    opacity: 0.7;
    color: #eee;
  }
}

.performance-item {
  margin-bottom: 15px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    display: block;
    margin-bottom: 5px;
    font-size: 14px;
  }
}

.quick-actions {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.activity-list {
  .activity-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid rgba(255, 255, 255, 0.08);
    &:last-child {
      border-bottom: none;
    }
    .activity-icon {
      margin-right: 8px;
      font-size: 18px;
      color: #67c23a;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 28px;
      height: 28px;
      background: rgba(103, 194, 58, 0.08);
      border-radius: 50%;
    }
    .activity-content {
      flex: 1;
      .activity-title {
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 1px;
        color: #fff;
      }
      .activity-time {
        font-size: 12px;
        opacity: 0.5;
        color: #eee;
      }
    }
  }
}

.alert-list {
  .alert-item {
    display: flex;
    align-items: flex-start;
    padding: 8px 0;
    border-bottom: 1px solid rgba(255, 255, 255, 0.08);
    &:last-child {
      border-bottom: none;
    }
    .alert-icon {
      margin-right: 8px;
      font-size: 18px;
      margin-top: 2px;
      width: 28px;
      height: 28px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.06);
    }
    .alert-content {
      flex: 1;
      .alert-title {
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 1px;
        color: #fff;
      }
      .alert-message {
        font-size: 12px;
        opacity: 0.7;
        color: #eee;
      }
    }
  }
}

.login-stats {
  .stat-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .stat-item {
      flex: 1;
      text-align: center;

      .stat-number {
        font-size: 24px;
        font-weight: bold;
        color: #67c23a;
        margin-bottom: 4px;
      }

      .stat-label {
        font-size: 12px;
        opacity: 0.7;
        color: #eee;
      }
    }
  }

  .login-trend {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);

    .trend-label {
      font-size: 14px;
      margin-bottom: 8px;
      color: #fff;
      font-weight: 500;
    }
  }
}

.dashboard-footer {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 15px 20px;
  margin-top: 15px;
  flex-shrink: 0;
  .footer-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    opacity: 0.8;
    flex-wrap: wrap;
    gap: 20px;

    .status-online {
      color: #67c23a;
      font-weight: bold;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .dashboard-content {
    grid-template-columns: 1fr !important;
    min-height: 0; // 确保在小屏下也有正确的高度
  }
  .left-panel,
  .right-panel {
    order: 2;
  }
  .center-panel {
    order: 1;
  }
}
@media (min-width: 1201px) {
  .dashboard-content {
    grid-template-columns: 1fr 2fr 1fr !important;
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }

  .dashboard-header {
    flex-direction: column;
    text-align: center;
    gap: 15px;
  }

  .header-title h1 {
    font-size: 24px;
  }

  .quick-actions {
    grid-template-columns: 1fr;
  }

  .business-metrics-card {
    .business-overview {
      .overview-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;

        .overview-item {
          padding: 12px;

          .overview-icon {
            width: 32px;
            height: 32px;
            font-size: 18px;
            margin-right: 8px;
          }

          .overview-content {
            .overview-number {
              font-size: 16px;
            }

            .overview-label {
              font-size: 11px;
            }
          }
        }
      }
    }
  }
}

// 图表容器样式
::v-deep .chart {
  background: transparent !important;
  width: 100% !important;
  height: 100% !important;
}

// 确保图表组件充分利用容器宽度
::v-deep .chart-container {
  width: 100% !important;
  height: 100% !important;
}

// 访问趋势分析和业务数据统计图表充分利用空间
.center-panel .chart-card .card-content {
  width: 100%;
}

.center-panel .chart-card .card-content .chart {
  width: 100% !important;
  max-width: none !important;
}

// Element UI 组件样式覆盖
::v-deep .el-button--text {
  color: #fff;

  &:hover {
    color: #67c23a;
  }
}

::v-deep .el-tag {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #fff;
}

::v-deep .el-progress-bar__outer {
  background: rgba(255, 255, 255, 0.2);
}

::v-deep .el-progress-bar__inner {
  background: linear-gradient(90deg, #67c23a, #e6a23c);
}

.business-metrics-card {
  margin-top: 0;
  margin-bottom: 0;

  .card-content {
    padding: 12px 16px 10px 16px; // 为业务数据统计卡片恢复左右padding
  }

  .business-overview {
    margin-bottom: 20px;

    .overview-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 15px;

      .overview-item {
        display: flex;
        align-items: center;
        padding: 15px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 8px;
        border: 1px solid rgba(255, 255, 255, 0.2);
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          background: rgba(255, 255, 255, 0.15);
        }

        .overview-icon {
          margin-right: 12px;
          font-size: 24px;
          color: #67c23a;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 40px;
          height: 40px;
          background: rgba(103, 194, 58, 0.1);
          border-radius: 50%;
        }

        .overview-content {
          flex: 1;

          .overview-number {
            font-size: 20px;
            font-weight: bold;
            color: #fff;
            margin-bottom: 2px;
          }

          .overview-label {
            font-size: 12px;
            opacity: 0.7;
            color: #eee;
          }
        }
      }
    }
  }

  .business-chart-container {
    margin-top: 15px;
  }
}

// 系统性能监控卡片特殊样式
.performance-monitor-card {
  .card-content {
    padding: 16px 20px 20px 20px; // 增加内边距
  }

  .gauge-container {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px; // 增加与下方进度条的间距
    min-height: 180px; // 确保有足够的高度
  }

  .performance-item {
    margin-bottom: 20px; // 增加进度条之间的间距

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      display: block;
      margin-bottom: 8px; // 增加标签与进度条的间距
      font-size: 14px;
      font-weight: 500; // 加粗标签
      color: #fff;
    }
  }
}

// 优化进度条样式
::v-deep .el-progress {
  .el-progress-bar__outer {
    background: rgba(255, 255, 255, 0.15);
    border-radius: 10px;
    height: 12px; // 增加进度条高度
  }

  .el-progress-bar__inner {
    border-radius: 10px;
    height: 12px;
    background: linear-gradient(90deg, #67c23a, #e6a23c, #f56c6c);
    transition: all 0.3s ease;
  }

  .el-progress__text {
    color: #fff;
    font-size: 14px;
    font-weight: bold;
  }
}
</style>
